/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package course.services;

import course.entities.User;
import course.entities.UserGroup;
import javax.enterprise.context.RequestScoped;
import javax.faces.bean.ManagedBean;

/**
 *
 * @author def
 */
@ManagedBean(name="createUserService")
@RequestScoped
public class CreateUserService extends AUserService {

    private User user;
    
    public CreateUserService() {
        this.user = new User();
    }

    public String createUser() {
        boolean available = userProvider.checkAvailability(user.getUserName());
        if (!available) {
            addErrorMessage("User \"" + user.getUserName() + "\" already exists");
            return "";
        } else {
            try {
                UserGroup group = groupProvider.findByGroupName("user");
                if (group == null) {
                    group = groupProvider.create();
                    group.setGroupName("user");
                    groupProvider.update(group);
                }
                group.getUsers().add(user);
                groupProvider.update(group);
                addInfoMessage("Thanks for registering, " + user.getUserName() + "!");
            } catch (Exception e) {
                addInfoMessage("DataProvider Error");
            }
        }
        return "/login";
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

}
